// mircoApp/shop_base/reward_template/index.js
let app = getApp();
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');

Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    activeName: 0,
    info: {
      member: {},
      statistic: {}
    },
    titleArr: [],
    dataList: [],
    finished: false,
    isLoadMore: true,

    minDate: new Date("2015/01/01").getTime(),
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    currentDateValue: '',
    showDatetime: false,
    datetime: false, //是否显示年月选择

    showPopList: false,
    poplistData: [],
    finishedPopList: false,
    poplistPage: 1,
    selectPopListItem: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  init() {
    
    this.data.dataList = [];
    this.data.titleArr = [];
    this.data.isLoadMore = true;
  },
  initList(){
    this.data.dataList[this.data.activeName].list = [];
    this.data.dataList[this.data.activeName].page = 1;
    this.data.dataList[this.data.activeName].isLoadMore = true;
  },
  getData() {
    console.log(this.options.extparams)
    let _parame = this.options.extparams?JSON.parse(this.options.extparams):{};
    console.log(_parame,'_parame')
    if (this.data.datetime && this.data.currentDateValue) {
      _parame = { ..._parame, datetime: this.data.currentDateValue }; //开启了年月筛选
    }
    let urlStr = app.getNetAddresss(this.options.api);
    app._postNetWork({
      url: urlStr,
      data: _parame||{},
      success: (resData) => {
        let res = resData.data;
        if (res.result !== 1) {
          return app.tips(res.msg);
        }
        let { tabArr, page_title, ...other} = res.data;
        
        try {
          // 后台-会员-推广中心设置（勾选端口访问不显示的页面，将强制跳转到跳转页面。若是没有设置跳转链接，则默认跳到商城首页。）
          let basic_info = {};
          if(res.basic_info) {
            basic_info = res.basic_info;
          }else {
            basic_info = wx.getStorageSync("yz_basic_info");
          }
          let _route = basic_info.popularize_page.mini.vue_route;
          let str = this.options.api;
          let parts = str.split('.');// 获取"plugin."和".frontend"之间的值，即索引1的元素
          let middleValue = parts[1];
          for (let i = 0; i < _route.length; i++) {
            if (_route[i].includes(middleValue)) {
              wx.showModal({
                title: '提示',
                content: '未开启推广权限',
                showCancel: false,
                success (res) {
                  wx.redirectTo({
                    url: basic_info.popularize_page.mini.mini_url,
                    fail: ()=> {
                      wx.redirectTo({
                        url: '/packageG/index/index'
                      });
                    }
                  });
                }
              });
              break;
              return;
            }
          }
        } catch (error) {
          console.log(error)
        }
        
        this.setData({
          info: other,
          // titleArr: tabArr
        });
        wx.setNavigationBarTitle({
          title: page_title
        })
        this.data.titleArr = tabArr;
        this.setNewArr();
      }
    });
  },
  setNewArr() {
    if(!this.data.titleArr) {
      return;
    }
    this.data.titleArr.forEach((val, index) => {
      this.data.dataList.push({
        isLoadMore: true,
        page: 1,
        total_page: 0,
        list: [],
        url: val.url,
        extParameter: val.extParameter
      });
    });
    this.handleClick();
  },
  onClick(event){
    this.setData({
      activeName: event.detail.index
    });
    this.handleClick();
  },

  handleClick() {
    if (this.data.dataList[this.data.activeName].list.length > 0) {
      this.data.isLoadMore = this.data.dataList[this.data.activeName].isLoadMore;
      return;
    }
    let urlStr = app.getNetAddresss(this.data.dataList[this.data.activeName].url);
    let _parameter1 = { page: 1 };
    let _parameter2 = this.data.dataList[this.data.activeName]?.extParameter||{};
    this.parameter = { ..._parameter1, ..._parameter2 };
    if(this.data.titleArr[this.data.activeName].search) {
      // 开启搜索框
      this.parameter[this.data.titleArr[this.data.activeName].search.queryString] = this.data.titleArr[this.data.activeName].search.name||'';
    }
    if (this.data.titleArr[this.data.activeName].dropdown) {
      // 开启菜单下拉框
      this.data.titleArr[this.data.activeName].dropdown.forEach(item => {
        this.parameter[item.name] = item.value;
      });
    }

    if (this.data.datetime && this.data.currentDateValue) {
      this.parameter.datetime = this.data.currentDateValue; //开启了年月筛选
    }
    let index = this.data.activeName;
    app._postNetWork({
      url: urlStr,
      data: this.parameter,
      success: (resData) => {
        let res = resData.data;
        if (res.result !== 1) {
          return app.tips(res.msg);
        }
        this.data.isLoadMore = true;
        this.data.dataList[index].isLoadMore = true;
        this.data.dataList[index].total_page = res.data.last_page;

        if (!this.data.dataList[index].total_page) {
          this.data.dataList[index].total_page = 0;
        }

        this.setData({
          ['dataList[' + index + '].list']: res.data.data,
          finished: res.data.data.length === 0,
          titleArr: this.data.titleArr
        });
      }
    });
  },

  //获取更多数据
  getMoreData() {
    this.data.dataList[this.data.activeName].isLoadMore = false;
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.dataList[this.data.activeName].page >= this.data.dataList[this.data.activeName].total_page) {
      return this.setData({
        finished: true
      });
    } else {
      this.data.dataList[this.data.activeName].page = this.data.dataList[this.data.activeName].page + 1;
      let _parameter1 = { page: this.data.dataList[this.data.activeName].page };
      let _parameter2 = this.data.dataList[this.data.activeName]?.extParameter || {};
      this.parameter = { ..._parameter1, ..._parameter2 };
      if(this.data.titleArr[this.data.activeName].search) {
        // 开启搜索框
        this.parameter[this.data.titleArr[this.data.activeName].search.queryString] = this.data.titleArr[this.data.activeName].search.name||'';
      }
      if (this.data.titleArr[this.data.activeName].dropdown) {
        // 开启菜单下拉框
        this.data.titleArr[this.data.activeName].dropdown.forEach(item => {
          this.parameter[item.name] = item.value;
        });
      }
      if (this.data.datetime && this.data.currentDateValue) {
        this.parameter.datetime = this.data.currentDateValue; //开启了年月筛选
      }
      let index = this.data.activeName;
      let urlStr = app.getNetAddresss(this.data.dataList[this.data.activeName].url);
      app._postNetWork({
        url: urlStr,
        data: this.parameter,
        success: (resData) => {
          this.data.isLoadMore = true;
          this.data.dataList[index].isLoadMore = true;
          let res = resData.data;
          if (res.result !== 1) {
            this.data.dataList[index].page = this.data.dataList[index].page - 1;
            this.data.dataList[index].isLoadMore = false;
            this.data.isLoadMore = false;
            return app.tips(res.msg);
          }
          let myData = res.data.data;
          this.data.dataList[index].list = this.data.dataList[index].list.concat(myData); //数组拼接
          this.setData({
            ['dataList[' + index + '].list']: this.data.dataList[index].list,
          });
        },fail: (res) => {
          console.log(res);
        },
      });
    }
  },
  onChangeDropdown(e){
    let {ind,index} = e.currentTarget.dataset;
    this.setData({
      ['titleArr[' + ind + '].dropdown[' + index + '].value']: e.detail
    });
    this.onSearch();
  },
  // 搜索框逻辑 --------------
  onInputSearch(e){
    this.data.titleArr[this.data.activeName].search.name = e.detail;
  },
  onSearch() {
    this.initList();
    this.handleClick();
  },
  onClearSearch(){
    this.parameter[this.data.titleArr[this.data.activeName].search.queryString] = '';
    this.setData({
      ['titleArr[' + this.data.activeName + '].search.name'] : ''
    });
  },
  // 搜索框逻辑 end  --------------
  // 列表点击事件 逻辑 --------------
  clickCol(e){
    let {datas:data,handletype} = e.currentTarget.dataset;
    // 把type单独解构出来，其余属性结构到navigateData对象中
    let { type, ...navigateData } = handletype == 1 ? this.data.titleArr[this.data.activeName]?.handle||{} : data;
    if(!type) {
      return;
    }
    if(type && type === 'navigateTo' ) {
      if(handletype == 2){
        return this.navigateToPage(data, data.popOptions); //点击跳转页面
      }
      this.navigateToPage(data,navigateData);//点击跳转页面
    } else if(type === "popList") {
      //显示弹窗列表
      this.initPopList();
      let _info = data;
      if(handletype == 1){
        _info = { popOptions: {...data, ...this.data.titleArr[this.data.activeName]?.handle?.popOptions }};
      }
      this.popList(_info);
    }
    // 其他 type ....
  },
  clickSubCol(e){
    let { datas:data, handletype, item } = e.currentTarget.dataset;
    // 把type单独解构出来，其余属性结构到navigateData对象中
    let { type, ...navigateData } = handletype == 1 ? this.data.titleArr[this.data.activeName]?.handle||{} : data;
    if(!type) {
      return;
    }
    // 如果data对象和item对象里都有api，则把data里的api覆盖item里的api
    if(data.api && item.api){
      item.api = data.api;
    }
    if(type && type === 'navigateTo' ) {
      if(handletype == 2){
        return this.navigateToPage(item, data.popOptions); //点击跳转页面
      }
      this.navigateToPage(item,navigateData);//点击跳转页面
    } else if(type === "popList") {
      //显示弹窗列表
      this.initPopList();
      let _info = item;
      if(handletype == 1){
        _info = { popOptions: {...item, ...this.data.titleArr[this.data.activeName]?.handle?.popOptions }};
      }
      this.popList(_info);
    }
    // 其他 type ....
  },
  delHandle(e){
    let {datas} = e.currentTarget.dataset;
    let params;
    if(datas.params.length > 0){
      datas.params.forEach((ele) => {
        if(ele && datas[ele]){
          params = {[ele]: datas[ele]}
        }
      });
    }
    this.listPost(datas.del_api,params);
  },
  async listPost(url,params) {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss(url),
      data:params
    });
    if ( data.result ) {
      this.init();
      this.getData();
    } else {
      app.tips(data.msg);
    }
  },
  navigateToPage(data,navigateData){
    let paramsData = {};
    let queryData = {};
    let { paramsKey, paramName, queryKey, queryName, mini_url } = navigateData;
    // 构建paramsData，用于router跳转时params传参
    paramsData = paramsKey.map((key, index) => `${paramName[index]}=${data[key]}`);

    // 构建queryData，用于router跳转时query传参
    queryData = queryKey.map((key, index) => `${queryName[index]}=${data[key]}`);
    paramsData = paramsData.join("&");
    queryData = queryData.join("&");
    console.log(paramsData);
    console.log(queryData);
    let _url = mini_url;
    if(paramsData) _url = `${mini_url}?${paramsData}&${queryData}`;
    if(!paramsData) _url = `${mini_url}?${queryData}`;
    console.log(_url);
    wx.navigateTo({ url: _url ,fail:(err)=>{
      console.log(err);
    }});
  },
  // 列表点击事件 end --------------
  clickDatetime() {
    this.setData({
      showDatetime: true
    });
  },
  setDateTime(ret) {
    this.setData({
      currentDateValue: this.timestampToTime(ret.detail),
      showDatetime: false,
      currentDate: ret.detail
    });
    this.init();
    this.getData();
  },
  clearDateTime() {
    this.setData({
      currentDateValue: '',
      showDatetime: false
    });
    this.init();
    this.getData();
  },
  //日期转化
  timestampToTime(timestamp) {
    var date = new Date(timestamp);
    let Y = date.getFullYear() + "-";
    let M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1);
    return Y + M;
  },
  // 弹窗列表 ----
  initPopList() {
    this.loadingPopList = false;
    this.setData({
      finishedPopList: false,
      poplistPage: 1,
      popListData: []
    });
  },
  popList(data){
    this.setData({
      selectPopListItem: data
    });
    this.onLoadPopList();
  },
  async onLoadPopList() {
    if(this.loadingPopList) return;//防止重复触底请求
    this.loadingPopList = true; 
    let { url, questKey = [], questName = [], ...otherData } = this.data.selectPopListItem?.popOptions || {};
    let _params = {
      page: this.data.poplistPage
    };
    for (let i = 0; i < questKey.length; i++) {
      let key = questKey[i];
      let name = questName[i];
      _params[name] = otherData[key];
    }
    let urlStr = app.getNetAddresss(url);
    app._getNetWork({
      url: urlStr,
      data: _params,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result !== 1) {
          return app.tips(res.msg);
        }
        this.loadingPopList = false;
        // 处理不是分页列表，只返回一个对象时，手动修改为数组
      if(!res.data.current_page) {
        this.data.poplistData = [];
        this.data.poplistData.push(res.data);
        this.setData({
          poplistData: this.data.poplistData,
          finishedPopList: true,
          showPopList: true,
        });
        return;
      }
      // 处理对象 end ----
        if (this.data.poplistPage == 1) {
          this.data.poplistData = []
        }
        let poplistData = this.data.poplistData.concat(res.data.data);
        this.setData({
          showPopList: true,
          poplistData,
        });
        this.data.poplistPage = this.data.poplistPage + 1;
        if (res.data.current_page == res.data.last_page) {
          this.setData({
            finishedPopList: true
          });
        }
        // 处理不是分页列表，只返回一个对象时，手动修改为数组
        if(!res.data.current_page) {
          this.setData({
            poplistData: this.data.poplistData(res.data),
            finishedPopList: true
          });
          return;
        }
        // 处理对象 end ----
      },fail: (res) => {
        this.loadingPopList = false;
        console.log(res);
      },
    });   
  },
  onClosePopList(){
    this.setData({
      showPopList: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(!this.options.api) {
      return app.tips('缺少必要参数');
    }
    if (this.options.date_time && this.options.date_time == 1) {
      this.setData({
        datetime: true,
        currentDateValue: this.timestampToTime(new Date().getTime())
      });
    }
    if(this.options.tabS) {
      this.setData({
        activeName: Number(this.options.tabS)
      });
    }
    this.init();
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let mini_url = `/mircoApp/shop_base/reward_template/index?api=${this.options.api}`;
    if(this.options.extparams) mini_url = mini_url + `&extparams=${this.options.extparams}` 
    return {
      path: mini_url
    }
  }
})